package com.mo.demo.ehcache;

import lombok.extern.slf4j.Slf4j;
import org.ehcache.Cache;
import org.ehcache.CacheManager;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;


@Slf4j
public class EhcacheExpireDemo2 {
    public static void main(String[] args) throws InterruptedException {
        CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
                .withCache("preConfigured", CacheConfigurationBuilder.newCacheConfigurationBuilder(Number.class, String.class, ResourcePoolsBuilder.heap(10))
                        .withExpiry(new MyExpiryPolicy<>())
                        .build())
                .build(true);

        Cache<Number, String> myCache = cacheManager.getCache("preConfigured", Number.class, String.class);

        myCache.put(1,"11");
        myCache.put(2,"22");

        log.info("初始状态：");
        printCacheState(myCache);

        new Thread(()->{
            try {
                loop(myCache);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        Thread.sleep(10000L);

        log.info("10秒后：");
        printCacheState(myCache);

        // 输出：
        // 14:05:33.251 [main] INFO com.mo.demo.ehcache.EhcacheExpireDemo2 - 初始状态：
        // 14:05:33.251 [main] INFO com.mo.demo.ehcache.EhcacheExpireDemo2 - key=1,value=11
        // 14:05:33.251 [main] INFO com.mo.demo.ehcache.EhcacheExpireDemo2 - key=2,value=22
        // 14:05:35.252 [Thread-0] INFO com.mo.demo.ehcache.EhcacheExpireDemo2 - 访问key=1
        // 14:05:37.253 [Thread-0] INFO com.mo.demo.ehcache.EhcacheExpireDemo2 - 访问key=1
        // 14:05:39.254 [Thread-0] INFO com.mo.demo.ehcache.EhcacheExpireDemo2 - 访问key=1
        // 14:05:41.256 [Thread-0] INFO com.mo.demo.ehcache.EhcacheExpireDemo2 - 访问key=1
        // 14:05:43.253 [main] INFO com.mo.demo.ehcache.EhcacheExpireDemo2 - 10秒后：
        // 14:05:43.253 [main] INFO com.mo.demo.ehcache.EhcacheExpireDemo2 - key=1,value=11
        // 14:05:43.258 [main] INFO com.mo.demo.ehcache.EhcacheExpireDemo2 - key=2,value=null
        // 14:05:43.258 [Thread-0] INFO com.mo.demo.ehcache.EhcacheExpireDemo2 - 访问key=1
        // 14:05:45.262 [Thread-0] INFO com.mo.demo.ehcache.EhcacheExpireDemo2 - 访问key=1
        // 14:05:47.266 [Thread-0] INFO com.mo.demo.ehcache.EhcacheExpireDemo2 - 访问key=1

    }

    private static void printCacheState(Cache<Number, String> myCache) {
        log.info("key={},value={}",1, myCache.get(1));
        log.info("key={},value={}",2, myCache.get(2));
    }

    private static void loop(Cache<Number, String> myCache) throws InterruptedException {
        Thread.sleep(2000L);
        log.info("访问key={}",1);
        myCache.get(1);
        loop(myCache);
    }
}
